import http from './http'

export interface KnowledgeDoc {
  id: string
  _id?: string // Compatibility
  title: string
  content: string
  category: string
  tags: string[]
  author: {
    _id: string
    username: string
  }
  status: 'draft' | 'published' | 'archived'
  viewCount: number
  likeCount: number
  createdAt: string
  updatedAt: string
}

export interface CreateKnowledgeDto {
  title: string
  content: string
  category: string
  tags?: string[]
  status?: 'draft' | 'published'
}

export interface UpdateKnowledgeDto extends Partial<CreateKnowledgeDto> {}

export interface KnowledgeQuery {
  search?: string
  category?: string
  tags?: string[]
  status?: string
  page?: number
  pageSize?: number
}

export interface AIQuestion {
  question: string
  context?: string
}

export interface AIAnswer {
  answer: string
  relatedDocs: KnowledgeDoc[]
  confidence: number
  sources: string[]
}

export const getKnowledgeDocs = async (params?: KnowledgeQuery) => {
  return await http.get('/knowledge', { params })
}

export const getKnowledgeDoc = async (id: string) => {
  return await http.get(`/knowledge/${id}`)
}

export const createKnowledgeDoc = async (data: CreateKnowledgeDto) => {
  return await http.post('/knowledge', data)
}

export const updateKnowledgeDoc = async (id: string, data: UpdateKnowledgeDto) => {
  return await http.put(`/knowledge/${id}`, data)
}

export const deleteKnowledgeDoc = async (id: string) => {
  return await http.delete(`/knowledge/${id}`)
}

export const askAI = async (data: AIQuestion) => {
  return await http.post('/knowledge/ai/ask', data)
}

export const getKnowledgeCategories = async () => {
  return await http.get('/knowledge/categories')
}

export const getPopularDocs = async () => {
  return await http.get('/knowledge/popular')
}
